# -*- coding: utf-8 -*-
from . import MyModelView
from flask_admin.contrib.sqla.filters import BooleanEqualFilter
from wtforms import PasswordField, TextField, ValidationError
from wtforms.validators import DataRequired
from flask_security.utils import hash_password
from flask_admin.form import rules
from sqlalchemy import func
from adminApp.models import User,roles_users, Role


class MyPassField(TextField):
    def process_data(self, value):
        self.data = ''
        self.orig_hash = value

    def process_formdata(self, valuelist):
        value = ''
        if valuelist:
            value = valuelist[0]
        if value:
            self.data = hash_password(value)
        else:
            self.data = self.orig_hash

class UserView(MyModelView):
    # 是否可以被导出
    # can_export = True
    # form_excluded_columns = ('password',)
    # 列标题
    column_list = ('id', 'name', 'email', 'active', 'created', 'updated')
    # 列标题
    column_labels = dict(
        name='用户名',
        email='电子邮箱',
        active='状态',
        created='创建日期',
        updated='更新日期',
        Roles='角色',
        password='密码'
    )
    column_formatters = dict(
        created=lambda v, c, m, p: m.created.strftime("%Y-%m-%d %H:%M:%S"),
        updated=lambda v, c, m, p: m.updated.strftime("%Y-%m-%d %H:%M:%S") if m.updated else ''
    )
    # 显示主键
    # column_display_pk = True
    # 不显示的字段
    column_exclude_list = ['password', ]
    form_args = dict(
        name=dict(validators=[DataRequired()]),
        email=dict(validators=[DataRequired()]),
        password=dict(validators=[DataRequired()]),
    )
    form_extra_fields = {
        'set_password': PasswordField('修改密码')
    }
    form_widget_args = dict(
        set_password=dict(
            placeholder='在此输入新密码以更改密码',
        ),
    )
    form_create_rules = _rules = ['roles', 'name', 'email', 'password', 'active']
    form_edit_rules = ['roles','name','email','set_password','active']

    def on_model_change(self, form, model, is_created):
        if not is_created:
            if self.session.query(func.count('*')).filter(User.id != model.id).filter(User.active == True).filter(
                    User.roles.any(name='superuser')).scalar() < 1:
                raise ValidationError('至少保留一个活动的超级管理员')
            if hasattr(form, 'set_password') and form.set_password.data:
                model.password = hash_password(form.set_password.data.strip())

    def on_model_delete(self, model):
        # 必须保留一个管理员
        if self.session.query(func.count('*')).filter(User.id != model.id).filter(User.active == True).filter(
                User.roles.any(name='superuser')).scalar() < 1:
            raise ValidationError('至少保留一个活动的超级管理员')


class RoleView(MyModelView):
    column_list = ('id', 'name', 'description', 'created', 'updated')
    column_labels = dict(
        name='角色名称',
        description='描述',
        created='创建日期',
        updated='更新日期',
    )
    column_formatters = dict(
        created=lambda v, c, m, p: m.created.strftime("%Y-%m-%d %H:%M:%S"),
        updated=lambda v, c, m, p: m.updated.strftime("%Y-%m-%d %H:%M:%S") if m.updated else ''
    )
    form_excluded_columns = ('created', 'updated')
    form_args = dict(
        name=dict(validators=[DataRequired()])
    )

    def on_model_change(self, form, model, is_created):
        if not is_created:
            old_role_name = self.session.query(Role.name).filter(Role.id == model.id).scalar()
            print(old_role_name)
            if old_role_name in ["superuser", 'user'] and model.name != old_role_name:
                raise ValidationError('不能修改此角色名称')

    def on_model_delete(self, model):
        # 角色不能删除
        if model.name in ["superuser", 'user']:
            raise ValidationError('内置角色不能删除')

    def edit_form(self, obj=None):
        frm = super().edit_form(obj)
        if frm.name.data in ["superuser", 'user']:
            if frm.name.render_kw:
                frm.name.render_kw['readonly'] = 'readonly'
            else:
                frm.name.render_kw = dict(readonly='readonly')
        return frm
